﻿var date_format_string = 'd/m/Y';
var date_sql_format_string = 'Y-m-d';
var page_size = 20;
var sumQuantity = 0;
var sumTotal = 0;
var sumComposer = 0;
var sumSinger = 0;
var sumRelease = 0;
var gridYieldRevenue;
var gridNotYieldRevenue;
var row_current = -1;
var col_current = -1;

/*
 * all Calculation methods are called on each Record in the Store
 * with the following 5 parameters:
 *
 * v - cell value
 * record - reference to the current Record
 * colName - column name (i.e. the ColumnModel's dataIndex)
 * data - the cumulative data for the current column + summaryType up to the current Record
 * rowIdx - current row index
 */
Ext.ux.grid.GridSummary.Calculations = {
    sum: function(v, record, colName, data, rowIdx){
		var result = 0;
		switch(colName){
			case 'exchange_quantity': result = sumQuantity; break;
			case 'money_total': result = sumTotal; break;
			case 'money_composer': result = sumComposer; break;
			case 'money_singer': result = sumSinger; break;
			case 'money_release': result = sumRelease; break;
		}
		return result;
    }
};

/*checkbox column*/
Ext.grid.CheckColumn = function(config){
    Ext.apply(this, config);
    if (!this.id) {
        this.id = Ext.id();
    }
    this.renderer = this.renderer.createDelegate(this);
};

Ext.grid.CheckColumn.prototype = {
    init: function(grid){
        this.grid = grid;
        this.grid.on('render', function(){
            var view = this.grid.getView();
            view.mainBody.on('mousedown', this.onMouseDown, this);
        }, this);
    },
    	
    onMouseDown: function(e, t){
        if (t.className && t.className.indexOf('x-grid3-cc-' + this.id) != -1) {
                e.stopEvent();
                var index = this.grid.getView().findRowIndex(t);
                var record = this.grid.store.getAt(index);  
				var checked = !record.data[this.dataIndex];
                record.set(this.dataIndex, checked);    
				if(isEmpty(record.data.exchange_id) || record.data.exchange_id == 0) {
					//Insert
					//insertExchange(record);
				}else{
					//Update
					var check_val = checked ? 1 : 0;
					updateExchange(record, this.dataIndex, check_val);
				};
        }
    },
    
    renderer: function(v, p, record){
        p.css += ' x-grid3-check-col-td';
        return '<div class="approved-column x-grid3-check-col' +
        (v ? '-on' : '') +
        ' x-grid3-cc-' +
        this.id +
        '">&#160;</div>';
    }
};
/*end of checkbox column*/

var cN = function(val){
    if (isEmpty(val)) {
        return 0;
    }
    if (is_string(val)) {
        if (val.indexOf(thousandSeparator) > 0) {
            val = val.replaceAll(thousandSeparator, decimalSeparator);
        }
        val = formatNumber(val);
    }
    return val;
};

var render_number = function(val){	
    try {
    	if (isEmpty(val)) val = 0.00;
        return number_format_extra(cN(val), decimals, decimalSeparator, thousandSeparator);
    } 
    catch (e) {
    }
};

Ext.apply(Ext.form.VTypes, {

    daterange: function(val, field){
        var date = field.parseDate(val);
        
        if (!date) {
            return;
        }
        if (field.startDateField && (!this.dateRangeMax || (date.getTime() != this.dateRangeMax.getTime()))) {
            var start = Ext.getCmp(field.startDateField);
            start.setMaxValue(date);
            start.validate();
            this.dateRangeMax = date;
        }
        else 
            if (field.endDateField && (!this.dateRangeMin || (date.getTime() != this.dateRangeMin.getTime()))) {
                var end = Ext.getCmp(field.endDateField);
                end.setMinValue(date);
                end.validate();
                this.dateRangeMin = date;
            }
        /*
         * Always return true since we're only using this vtype to set the
         * min/max allowed values (these are tested for after the vtype test)
         */
        return true;
    }
});

//----------------------------------------------------------------------------------------------------
var pathRequestUrl;
Ext.onReady(function(){
    Ext.QuickTips.init();
    	
    pathRequestUrl = 'YieldRevenueInformation_Data.php';
	
	var formatDate = function(value){
        if (isEmpty(value)) 
            return '';
        try {
            return value ? ((value.dateFormat('m/Y') != '01/1970') ? value.dateFormat('m/Y') : '') : '';
        } 
        catch (e) {
            console.debug(e);
        }
    };
	
	//Design delete button for grid
    Ext.ns('Extensive.grid');
    Extensive.grid.ItemDeleter = Ext.extend(Ext.grid.RowSelectionModel, {
        width: 30,
        sortable: false,
        dataIndex: 0, // this is needed, otherwise there will be an error		
        menuDisabled: true,
        fixed: true,
        id: 'deleter',
        initEvents: function(){
            Extensive.grid.ItemDeleter.superclass.initEvents.call(this);
            this.grid.on('cellclick', function(grid, rowIndex, columnIndex, e){
                if (columnIndex == grid.getColumnModel().getIndexById('deleter')) {
                    var record = grid.getStore().getAt(rowIndex);
                    if (record.data.exchange_id == 0) 
                        return false;
                    Ext.Msg.show({
                        title: 'Xác nhận',
                        buttons: Ext.MessageBox.YESNO,
                        icon: Ext.MessageBox.QUESTION,
                        msg: "Bạn có chắc là muốn xóa <b>" + record.data.song_number + "</b> không ?",
                        fn: function(btn){
                            if (btn == 'yes') {
                                deleteExchange(record);
                            }
                        }
                    });                    
                }
            });
        },
        renderer: function(v, p, record, rowIndex){
            return '<div class="extensive-remove" style="width: 15px; height: 16px;"></div>';
        }
    });
    var itemDeleter = new Extensive.grid.ItemDeleter();
    
	//Bai hat:----------------------------------------   
    var storeSongNumber = new Ext.data.Store({
        reader: new Ext.data.JsonReader({
            root: 'data',
            totalProperty: 'count',
            id: 'song_id',
            fields: ['song_id', 'song_number', 'song_name']
        }),
        proxy: new Ext.data.HttpProxy({
            url: pathRequestUrl
        }),
        autoLoad: false
    });
	
	storeSongNumber.on('beforeload', function(store){
        store.baseParams.action = 'getListSongNumber';
    });
	
	var storeSongName = new Ext.data.Store({
        reader: new Ext.data.JsonReader({
            root: 'data',
            totalProperty: 'count',
            id: 'song_id',
            fields: ['song_id', 'song_number', 'song_name']
        }),
        proxy: new Ext.data.HttpProxy({
            url: pathRequestUrl
        }),
        autoLoad: false
    });
		
	storeSongName.on('beforeload', function(store){
        store.baseParams.action = 'getListSongName';
    });
	
	var tpl_song = new Ext.XTemplate('<tpl for="."><div class="search-item"><div style="float:left; width:55px;">{song_number}</div><div style="float:left; text-align:left;">| </div><div>{song_name}</div></div></tpl>');
	
	var render_song_number_tooltip = function(v, p, a){
        if (isEmpty(v)) 
            return;
        p.attr = 'ext:qtitle="<u>Mã Bài Hát</u>"';
        p.attr += 'ext:qtip="' + v + '"';
        return v;
    };
	
	var render_song_name_tooltip = function(v, p, a){
        if (isEmpty(v)) 
            return;
        p.attr = 'ext:qtitle="<u>Tên Bài Hát</u>"';
        p.attr += 'ext:qtip="' + v + '"';
        return v;
    };
	
	//Ca si:----------------------------------------   
    var storeSinger = new Ext.data.Store({
        reader: new Ext.data.JsonReader({
            root: 'data',
            totalProperty: 'count',
            id: 'object_id',
            fields: ['object_id', 'object_number', 'object_name', 'object_type']
        }),
        proxy: new Ext.data.HttpProxy({
            url: pathRequestUrl
        }),
        autoLoad: false
    });
	
	storeSinger.on('beforeload', function(store){
        store.baseParams.action = 'getListSinger';
    });
	
	var render_singer_tooltip = function(v, p, a){
        //v : value , p : cell		
        if (isEmpty(v)) 
            return;
        p.attr = 'ext:qtitle="<u>Ca Sĩ</u>"';
        p.attr += 'ext:qtip="' + v + '"';
        return v;
    };
	
	//Nhac si:----------------------------------------   
    var storeComposer = new Ext.data.Store({
        reader: new Ext.data.JsonReader({
            root: 'data',
            totalProperty: 'count',
            id: 'object_id',
            fields: ['object_id', 'object_number', 'object_name', 'object_type']
        }),
        proxy: new Ext.data.HttpProxy({
            url: pathRequestUrl
        }),
        autoLoad: false
    });
	
	storeComposer.on('beforeload', function(store){
        store.baseParams.action = 'getListComposer';
    });
	
	var render_composer_tooltip = function(v, p, a){
        //v : value , p : cell		
        if (isEmpty(v)) 
            return;
        p.attr = 'ext:qtitle="<u>Nhạc Sĩ</u>"';
        p.attr += 'ext:qtip="' + v + '"';
        return v;
    };
	
	//Partner----------------------------------------------	
    var partnerRecord = [{
        name: 'partner_id',
        type: 'string'
    }, {
        name: 'partner_number',
        type: 'string'
    }, {
        name: 'partner_name',
        type: 'string'
    }];
    
    var partnerObj = Ext.data.Record.create(partnerRecord);
    
    var storePartner = new Ext.data.Store({
        reader: new Ext.data.JsonReader({
            root: 'data',
            totalProperty: 'count',
            id: 'partner_id'
        }, partnerObj),
        proxy: new Ext.data.HttpProxy({
            url: pathRequestUrl
        }),
        autoLoad: true
    });
    
    storePartner.on('beforeload', function(){
        storePartner.baseParams.action = 'getPartner';
    });
    
    var partnerPriceRecord = [{
        name: 'id',
        type: 'string'
    }, {
        name: 'price',
        type: 'string'
    }];
    
    var partnerPriceObj = Ext.data.Record.create(partnerPriceRecord);
    
    var storePartnerPrices = new Ext.data.Store({
        reader: new Ext.data.JsonReader({
            root: 'data',
            id: 'id'
        }, partnerPriceObj),
        proxy: new Ext.data.HttpProxy({
            url: pathRequestUrl
        }),
        autoLoad: false
    });
    
    storePartnerPrices.on('beforeload', function(){
        storePartnerPrices.baseParams.action = 'getPartnerPrices';
    });
    
	var render_partner_tooltip = function(v, p, a){
        try {
            if (isEmpty(v) || (v == 0)) {
                return '';
            }
            
            var partnerObj = storePartner.queryBy(function(rec){
                return rec.data.partner_id == v;
            }).itemAt(0);
            if (partnerObj && !isEmpty(v)) {
                v = partnerObj.data.partner_name;
                p.attr = 'ext:qtitle="<u>Đối Tác</u>"';
                p.attr += 'ext:qtip="' + v + '"';
                return v;
            }
            return '';
        } 
        catch (e) {
        }
    };
    
    var storeObject = new Ext.data.Store({
        reader: new Ext.data.JsonReader({
            root: 'data',
            totalProperty: 'count',
            id: 'object_id',
            fields: ['object_id', 'object_number', 'object_name']
        }),
        proxy: new Ext.data.HttpProxy({
            url: pathRequestUrl
        }),
        autoLoad: true
    });
    
    storeObject.on('beforeload', function(){
        storeObject.baseParams.start = 0;
        storeObject.baseParams.limit = page_size;
        storeObject.baseParams.action = 'getObject';
    });
    
    var resultTplObject = new Ext.XTemplate('<tpl for="."><div class="search-item">', '<span>{object_number} | {object_name}</span><br />', '</div></tpl>');
    
    var cbObject = new Ext.form.ComboBox({
        id: 'cbObject',
        store: storeObject,
        fieldLabel: 'Tên',
        forceSelection: true,
        displayField: 'object_name',
        valueField: 'object_id',
        typeAhead: false,
        triggerAction: 'all',
        emptyText: 'Chọn tên',
        allowBlank: false,
        tpl: resultTplObject,
        selectOnFocus: true,
        editable: true,
        width: 130,
        pageSize: page_size,
        lazyRender: true,
        listWidth: 400,
        itemSelector: 'div.search-item',
        minChars: 1,
        listeners: {
            select: function(combo, record, index){
            
            },
            change: function(e){
            	gridYieldRevenue.getStore().load();
            }
        }
    });
	
	var cbObject2 = new Ext.form.ComboBox({
        id: 'cbObject2',
        store: storeObject,
        fieldLabel: 'Tên',
        forceSelection: true,
        displayField: 'object_name',
        valueField: 'object_id',
        typeAhead: false,
        triggerAction: 'all',
        emptyText: 'Chọn tên',
        allowBlank: false,
        tpl: resultTplObject,
        selectOnFocus: true,
        editable: true,
        width: 130,
        pageSize: page_size,
        lazyRender: true,
        listWidth: 400,
        itemSelector: 'div.search-item',
        minChars: 1,
        listeners: {
            select: function(combo, record, index){
            
            },
            change: function(e){
            	gridNotYieldRevenue.getStore().load();
            }
        }
    });
    
    var cbSubjectName = new Ext.form.ComboBox({
        id: 'cbSubjectName',
        name: 'cbSubjectName',
        store: storePartner,
        fieldLabel: 'Đối tác',
        forceSelection: true,
        displayField: 'partner_name',
        valueField: 'partner_id',
        allowBlank: false,
        typeAhead: true,
        mode: 'local',
        triggerAction: 'all',
        emptyText: 'Chọn đối tác',
        selectOnFocus: true,
        editable: false,
        width: 120,
        minListWidth: 300,
        lazyRender: true,
        listeners: {
            select: function(combo, record, index){
		Ext.getCmp('cbPartnerPrices').setValue('');
		storePartnerPrices.load({
		    params: {partner_id: record.data.partner_id}
		})
            },
            change: function(e){
            	//gridYieldRevenue.getStore().load();
            }
        }
    });
    
    var cbPartnerPrices = new Ext.form.ComboBox({
        id: 'cbPartnerPrices',
        name: 'cbPartnerPrices',
        store: storePartnerPrices,
        fieldLabel: 'Giá',
        forceSelection: true,
        displayField: 'price',
        valueField: 'id',
        allowBlank: true,
        typeAhead: true,
        mode: 'local',
        triggerAction: 'all',
        emptyText: 'Chọn giá',
        selectOnFocus: true,
        editable: true,
        width: 80,
        minListWidth: 300,
        lazyRender: true,
        listeners: {
            select: function(combo, record, index){            
            },
            change: function(e){
            }
        }
    });
    
	var cbSubjectName2 = new Ext.form.ComboBox({
        id: 'cbSubjectName2',
        name: 'cbSubjectName2',
        store: storePartner,
        fieldLabel: 'Đối tác',
        forceSelection: true,
        displayField: 'partner_name',
        valueField: 'partner_id',
        allowBlank: false,
        typeAhead: true,
        mode: 'local',
        triggerAction: 'all',
        emptyText: 'Chọn đối tác',
        selectOnFocus: true,
        editable: false,
        width: 120,
        minListWidth: 300,
        lazyRender: true,
        listeners: {
            select: function(combo, record, index){
		Ext.getCmp('cbPartnerPrices').setValue('');
		storePartnerPrices.load({
		    params: {partner_id: record.data.partner_id}
		})
            },
            change: function(e){
            	//gridYieldRevenue.getStore().load();
            }
        }
        
    });
	
    var cbPartnerPrices2 = new Ext.form.ComboBox({
        id: 'cbPartnerPrices2',
        name: 'cbPartnerPrices2',
        store: storePartnerPrices,
        fieldLabel: 'Giá',
        forceSelection: true,
        displayField: 'price',
        valueField: 'id',
        allowBlank: true,
        typeAhead: true,
        mode: 'local',
        triggerAction: 'all',
        emptyText: 'Chọn giá',
        selectOnFocus: true,
        editable: true,
        width: 80,
        minListWidth: 300,
        lazyRender: true,
        listeners: {
            select: function(combo, record, index){            
            },
            change: function(e){
            }
        }
    });
	
    var generalTab = new Ext.Panel({
        frame: true,
        title: '',
        id: 'generalTab',
        items: [{
            layout: 'column',
            items: [{
                columnWidth: .2,
                layout: 'form',
                labelWidth: 70,
                items: [{
                    xtype: 'hidden',
                    id: 'selectedTimeValue',
                    value: '1'
                }, new Ext.form.RadioGroup({
                    fieldLabel: 'Thời gian',
                    columns: 1,
                    id: "timename",
                    items: [{
                        boxLabel: 'Tháng',
                        name: 'timename',
                        inputValue: 'month',
                        checked: true
                    }, {
                        boxLabel: 'Quý',
                        name: 'timename',
                        inputValue: 'quarter'
                    }, {
                        boxLabel: 'Từ tháng',
                        name: 'timename',
                        inputValue: 'frommonth'
                    }]
                })]
            }, {
                columnWidth: .5,
                layout: 'form',
                labelWidth: 5,
                id: 'col1',
                items: [{
                    layout: 'column',
                    items: [{
                        columnWidth: .25,
                        layout: 'form',
                        labelWidth: 5,
                        items: [{
                            xtype: 'spinnerfield',
                            name: 'month2',
                            id: 'month2',
                            width: 70,
                            length: 4,
                            minValue: 1,
                            maxValue: 12,
                            allowDecimals: false,
                            incrementValue: 1,
                            accelerate: true,
                            value: (new Date()).format('m')
                        }]
                    }, {
                        columnWidth: .7,
                        layout: 'form',
                        labelWidth: 30,
                        items: [{
                            xtype: 'spinnerfield',
                            name: 'year2',
                            id: 'year2',
                            width: 70,
                            length: 4,
                            minValue: 2010,
                            maxValue: 2020,
                            allowDecimals: false,
                            incrementValue: 1,
                            accelerate: true,
                            fieldLabel: 'Năm',
                            value: (new Date()).format('Y')
                        }]
                    }]
                }, {
                    layout: 'column',
                    items: [{
                        columnWidth: .25,
                        layout: 'form',
                        labelWidth: 5,
                        items: [{
                            xtype: 'spinnerfield',
                            name: 'quarter3',
                            id: 'quarter3',
                            width: 70,
                            length: 4,
                            minValue: 1,
                            maxValue: 4,
                            allowDecimals: false,
                            incrementValue: 1,
                            accelerate: true,
                            value: 1
                        }]
                    }, {
                        columnWidth: .7,
                        layout: 'form',
                        labelWidth: 30,
                        items: [{
                            xtype: 'spinnerfield',
                            name: 'year3',
                            id: 'year3',
                            width: 70,
                            length: 4,
                            minValue: 2010,
                            maxValue: 2020,
                            allowDecimals: false,
                            incrementValue: 1,
                            accelerate: true,
                            fieldLabel: 'Năm',
                            value: (new Date()).format('Y')
                        }]
                    }]
                }, {
                    layout: 'column',
                    items: [{
                        columnWidth: .22,
                        layout: 'form',
                        labelWidth: 5,
                        items: [{
                            xtype: 'spinnerfield',
                            name: 'frommonth7',
                            id: 'frommonth7',
                            width: 70,
                            length: 4,
                            minValue: 1,
                            maxValue: 12,
                            allowDecimals: false,
                            incrementValue: 1,
                            accelerate: true,
                            value: (new Date()).format('m')
                        }]
                    }, {
                        columnWidth: .25,
                        layout: 'form',
                        labelWidth: 5,
                        items: [{
                            xtype: 'spinnerfield',
                            name: 'fromyear7',
                            id: 'fromyear7',
                            width: 70,
                            length: 4,
                            minValue: 2010,
                            maxValue: 2020,
                            allowDecimals: false,
                            incrementValue: 1,
                            accelerate: true,
                            value: (new Date()).format('Y')
                        }]
                    }, {
                        columnWidth: .27,
                        layout: 'form',
                        labelWidth: 20,
                        items: [{
                            xtype: 'spinnerfield',
                            name: 'tomonth7',
                            id: 'tomonth7',
                            width: 70,
                            length: 4,
                            minValue: 1,
                            maxValue: 12,
                            labelSeparator: '',
                            fieldLabel: 'Đến',
                            allowDecimals: false,
                            incrementValue: 1,
                            accelerate: true,
                            value: (new Date()).format('m')
                        }]
                    }, {
                        columnWidth: .25,
                        layout: 'form',
                        labelWidth: 5,
                        items: [{
                            xtype: 'spinnerfield',
                            name: 'toyear7',
                            id: 'toyear7',
                            width: 70,
                            length: 4,
                            minValue: 2010,
                            maxValue: 2020,
                            allowDecimals: false,
                            incrementValue: 1,
                            accelerate: true,
                            value: (new Date()).format('Y')
                        }]
                    }]
                }]
            }]
        }]
    });
    
    var YieldRevenue = {
        newRow: function(){
        
        },
        addNew: function(){
        
        },
        find: function(){
        
        },
        remove: function(){
        
        }
    };
    
    var storeAuthority = new Ext.data.ArrayStore({
        fields: [{
            name: 'authority'
        }, {
            name: 'name'
        }, ],
        data: [[1, 'Quyền ghi âm'], [2, 'Quyền tác giả'], [3, 'Cả hai quyền']]
    });
	
	var storeRelease = new Ext.data.ArrayStore({
        fields: [{
            name: 'release'
        }, {
            name: 'name'
        }, ],
        data: [[0, 'Không độc quyền'], [1, 'Độc quyền']]
    });
    
    var yieldRecord = [{
        name: 'exchange_id',
        type: 'string'
    },{
        name: 'exchange_imported_date',
        type: 'string'
    },{
        name: 'partner_id',
        type: 'string'
    },{
        name: 'partner_name',
        type: 'string'
    },{
        name: 'song_id',
        type: 'string'
    },{
        name: 'song_number',
        type: 'string'
    },{
        name: 'song_name',
        type: 'string'
    },{
        name: 'singer_id',
        type: 'string'
    },{
        name: 'singer_name',
        type: 'string'
    },{
        name: 'song_singer_sing',
        type: 'string'
    },{
        name: 'composer_id',
        type: 'string'
    },{
        name: 'composer_name',
        type: 'string'
    },{
        name: 'exchange_price',
        type: 'string'
    },{
        name: 'exchange_quantity',
        type: 'string'
    },{
        name: 'song_singer_authority',
        type: 'string'
    },{
        name: 'song_composer_authority',
        type: 'string'
    },{
        name: 'song_release_authority',
        type: 'string'
    },{
        name: 'money_total',
        type: 'string'
    },{
        name: 'money_composer',
        type: 'string'
    },{
        name: 'money_singer',
        type: 'string'
    },{
        name: 'money_release',
        type: 'string'
    },{
        name: 'sum_exchange_quantity',
        type: 'string'
    },{
        name: 'sum_money_total',
        type: 'string'
    },{
        name: 'sum_money_composer',
        type: 'string'
    },{
        name: 'sum_money_singer',
        type: 'string'
    },{
        name: 'sum_money_release',
        type: 'string'
    }];
    
    var yield_object = Ext.data.Record.create(yieldRecord);
    
    var storeYieldRevenue = new Ext.data.Store({
        reader: new Ext.data.JsonReader({
            root: 'data',
            totalProperty: 'count',
			id: 'exchange_id'
        }, yield_object),
        proxy: new Ext.data.HttpProxy({
            url: pathRequestUrl
        }),
        autoLoad: true
    });
    
    storeYieldRevenue.on('beforeload', function(){
        var fd = baseGetFromDateRank();
        var td = baseGetToDateRank();
        if (!isEmpty(fd) && !isEmpty(td) &&
        !isEmpty(Ext.getCmp('cbSubjectName').getValue())) {
            storeYieldRevenue.baseParams.start = 0;
            storeYieldRevenue.baseParams.limit = page_size;
            storeYieldRevenue.baseParams.action = 'getYieldRevenue';
            storeYieldRevenue.baseParams.fromdate = fd;
            storeYieldRevenue.baseParams.todate = td;
            storeYieldRevenue.baseParams.partner = Ext.getCmp('cbSubjectName').getValue();
	    storeYieldRevenue.baseParams.partnerPrice = Ext.getCmp('cbPartnerPrices').getRawValue();
            storeYieldRevenue.baseParams.object = Ext.getCmp('cbObject').getValue();
            storeYieldRevenue.baseParams.type = Ext.getCmp('object_type').getValue().inputValue;
            storeYieldRevenue.baseParams.authority = isEmpty(Ext.getCmp('cboPermission').getValue()) ? 0 : Ext.getCmp('cboPermission').getValue();
	    storeYieldRevenue.baseParams.release = isEmpty(Ext.getCmp('cboRelease').getValue()) ? -1 : Ext.getCmp('cboRelease').getValue();
        }
    });
    
	storeYieldRevenue.on('load', function(){		
		if(storeYieldRevenue.getCount() > 0){
			var row = gridYieldRevenue.store.getAt(0);
			sumQuantity = row.data.sum_exchange_quantity;
			sumTotal = row.data.sum_money_total;
			sumComposer = row.data.sum_money_composer;
			sumSinger = row.data.sum_money_singer;
			sumRelease = row.data.sum_money_release;
			gridYieldRevenue.getView().refresh(true);
		}
    });
    
    var tbarYieldRevenue = new Ext.Toolbar({
        items: [{
            xtype: 'label',
            text: 'Đối tác',
            style: 'padding-left: 5px; padding-right: 5px;'
        }, cbSubjectName, {
            xtype: 'label',
            text: 'Giá',
            style: 'padding-left: 5px; padding-right: 5px;'
        }, cbPartnerPrices, '-', {
            xtype: 'label',
            text: 'Tên ca sĩ/nhạc sĩ',
            style: 'padding-left: 5px; padding-right: 5px;'
        }, cbObject, '-', {
            xtype: 'radiogroup',
            id: 'object_type',
            value: 1,
            items: [{
                boxLabel: 'Ca sĩ',
                name: 'rb-type',
                width: 80,
                inputValue: 1                
            }, {
                boxLabel: 'Nhạc sĩ',
                name: 'rb-type',
                inputValue: 2
            }],
            listeners: {
                change: function(e){
        			gridYieldRevenue.getStore().load();
                }
            }
        }, '-', {
            xtype: 'label',
            text: 'Loại quyền',
            style: 'padding-left: 5px; padding-right: 5px;'
        }, new Ext.form.ComboBox({
            id: 'cboPermission',
            store: storeAuthority,
            forceSelection: true,
            displayField: 'name',
            valueField: 'authority',
            typeAhead: false,
            triggerAction: 'all',
            mode: 'local',
            allowBlank: true,
            editable: true,
            width: 100,
            minListWidth: 100,
            lazyRender: true,
            selectOnFocus: true,
            listeners: {
                select: function(combo, record, index){
                
                },
                change: function(e){
                	gridYieldRevenue.getStore().load();
                }
            }
        }), '-', {
            xtype: 'label',
            text: 'Độc quyền',
            style: 'padding-left: 5px; padding-right: 5px;'
        }, new Ext.form.ComboBox({
            id: 'cboRelease',
            store: storeRelease,
            forceSelection: true,
            displayField: 'name',
            valueField: 'release',
            typeAhead: false,
            triggerAction: 'all',
            mode: 'local',
            allowBlank: true,
            editable: true,
            width: 100,
            minListWidth: 100,
            lazyRender: true,
            selectOnFocus: true,
            listeners: {
                select: function(combo, record, index){
                
                },
                change: function(e){
                	gridYieldRevenue.getStore().load();
                }
            }
        }), '->', {
            text: 'In',
            id: 'printer_add',
            cls: 'x-btn-text-icon',
            icon: 'images/icons/printer.png',
			handler: function(){
				if(!isEmpty(Ext.getCmp('cbSubjectName').getValue())){
					var action = 'exportYieldRevenue';
					var fromdate = baseGetFromDateRank();
					var todate = baseGetToDateRank();
					var partner = Ext.getCmp('cbSubjectName').getValue();
					var partnerPrice = Ext.getCmp('cbPartnerPrices').getRawValue();
					var partnerPriceId = Ext.getCmp('cbPartnerPrices').getValue();
					var object = isEmpty(Ext.getCmp('cbObject').getValue()) ? -1 : Ext.getCmp('cbObject').getValue();
					var type = Ext.getCmp('object_type').getValue().inputValue;
					var authority = isEmpty(Ext.getCmp('cboPermission').getValue()) ? 0 : Ext.getCmp('cboPermission').getValue();
					var release = isEmpty(Ext.getCmp('cboRelease').getValue()) ? -1 : Ext.getCmp('cboRelease').getValue();
					window.open(pathRequestUrl + '?action=' + action +
						    '&partner=' + partner +
						    '&partnerPrice=' + partnerPrice +
						    '&partnerPriceId=' + partnerPriceId +
						    '&object=' + object + 
					'&type=' + type + '&authority=' + authority + '&release=' + release + '&fdate=' + fromdate + '&tdate=' + todate, null, "height=200,width=400,status=yes,toolbar=no,menubar=no,location=no");
				}else{
					warning('Cảnh báo', 'Vui lòng chọn Đối tác.');
				}				
			}
        }, '-', {
            text: 'Tải lại',
            id: 'reload_detail',
            iconCls: 'btn-text-icon',
            icon: './images/icons/refresh.png',
            handler: function(){
                storeYieldRevenue.removeAll();
                storeYieldRevenue.load();
            }
        }]
    });
    
	var summary = new Ext.ux.grid.GridSummary();
	
    var cmbPerPage = new Ext.form.ComboBox({
        name: 'perpage',
        width: 80,
        store: new Ext.data.SimpleStore({
            data: [[20, '20'], [50, '50'], [100, '100'], [300, '300'], [500, '500'], [1000, '1000']],
            id: 0,
            fields: ['id', 'value']
        }),
        mode: 'local',
        value: '20',
        listWidth: 80,
        triggerAction: 'all',
        displayField: 'value',
        valueField: 'value',
        editable: false,
        forceSelection: true
    });
    
    cmbPerPage.on('select', function(combo, record){
        bbarYieldRevenue.pageSize = parseInt(record.get('id'), 10);
        bbarYieldRevenue.doLoad(bbarYieldRevenue.cursor);
    }, this);
    
    var bbarYieldRevenue = new Ext.PagingToolbar({
        store: storeYieldRevenue, //the store you use in your grid
        displayInfo: true,
        pageSize: page_size,
        items: ['-', 'Số dòng/trang', cmbPerPage]
    });
	
	var singerAuthority = new Ext.grid.CheckColumn({
            header: 'Quyền ghi âm',
            dataIndex: 'song_singer_authority',
            id: 'song_singer_authority',
            width: 60
    });
	var composerAuthority = new Ext.grid.CheckColumn({
            header: 'Quyền tác giả',
            dataIndex: 'song_composer_authority',
            id: 'song_composer_authority',
            width: 60
    });
	var composerRelease = new Ext.grid.CheckColumn({
        header: 'Độc quyền',
        dataIndex: 'song_release_authority',
        id: 'song_release_authority',
        width: 60
});
    
    var cmYieldRevenue = new Ext.grid.ColumnModel({
        defaults: {
            sortable: false
        },
        columns: [new Ext.grid.RowNumberer(), itemDeleter, {
            header: 'Tháng',
			dataIndex: 'exchange_imported_date',
            id: 'exchange_imported_date',
			width: 60,
			hidden: true
        }, {
            header: 'Đối tác',
			dataIndex: 'partner_id',
			width: 50,
			hidden: true,
			renderer: render_partner_tooltip/*,
			editor: new Ext.form.ComboBox({
                typeAhead: true,
                store: storePartner,
                valueField: 'partner_id',
                displayField: 'partner_name',
                mode: 'local',
                forceSelection: true,
                triggerAction: 'all',
                editable: true,
                width: 183,
                lazyRender: true,
                selectOnFocus: true,
                allowBlank: true,
                listeners: {
                    select: function(combo, record, index){
                        gridYieldRevenue.startEditing(row_current, col_current);
                    }
                }
            })*/
        }, {
            header: 'Mã bài hát',
			dataIndex: 'song_number',
            id: 'song_number',
			width: 50,
			renderer: render_song_number_tooltip/*,
            editor: new Ext.form.ComboBox({
				store: storeSongNumber,	                        
				forceSelection: true,		                        
				valueField: 'song_number',
                displayField: 'song_number',                        
				typeAhead: false,		                        
				triggerAction: 'all',		                        
				pageSize: 20,		                        
				tpl: tpl_song,		                        
				selectOnFocus: true,		                        
				editable: true,		                        
				width: 117,
                listWidth: 250,                        
				lazyRender: true,		                        
				itemSelector: 'div.search-item',		                        
				minChars: 1,	                    
		        allowBlank: true,
		        listeners: {
		            select: function(combo, record, index){
		            	gridYieldRevenue.getStore().getAt(row_current).data.song_id = record.data.song_id;
						gridYieldRevenue.startEditing(row_current, col_current);
		            }
		        }
	        })*/
        }, {
            header: 'Tên bài hát',
			dataIndex: 'song_name',
            id: 'song_name',
			renderer: render_song_name_tooltip/*,
            editor: new Ext.form.ComboBox({
				store: storeSongName,	                        
				forceSelection: true,		                        
				valueField: 'song_name',
                displayField: 'song_name',                        
				typeAhead: false,		                        
				triggerAction: 'all',		                        
				pageSize: 20,		                        
				tpl: tpl_song,		                        
				selectOnFocus: true,		                        
				editable: true,		                        
				width: 117,
                listWidth: 250,                        
				lazyRender: true,		                        
				itemSelector: 'div.search-item',		                        
				minChars: 1,	                    
		        allowBlank: true,
		        listeners: {
		            select: function(combo, record, index){
		            	gridYieldRevenue.getStore().getAt(row_current).data.song_id = record.data.song_id;
						gridYieldRevenue.startEditing(row_current, col_current);
		            }
		        }
	        })*/
        }, {
            header: 'Ca sĩ',
			dataIndex: 'singer_name',
            id: 'singer_name',
			renderer: render_singer_tooltip/*,
            editor: new Ext.form.ComboBox({
				store: storeSinger,	                        
				forceSelection: true,		                        
				valueField: 'object_name',
                displayField: 'object_name',                        
				typeAhead: false,		                        
				triggerAction: 'all',		                        
				pageSize: 20,		                        
				tpl: resultTplObject,		                        
				selectOnFocus: true,		                        
				editable: true,		                        
				width: 117,
                listWidth: 250,                        
				lazyRender: true,		                        
				itemSelector: 'div.search-item',		                        
				minChars: 1,	                    
		        allowBlank: true,
		        listeners: {
		            select: function(combo, record, index){
		            	gridYieldRevenue.getStore().getAt(row_current).data.singer_id = record.data.object_id;
						gridYieldRevenue.startEditing(row_current, col_current);
		            }
		        }
	        })*/
        }, {
            header: 'Ca sĩ thể hiện',
			dataIndex: 'song_singer_sing',
            id: 'song_singer_sing'
		}, {
            header: 'Nhạc sĩ',
			dataIndex: 'composer_name',
            id: 'composer_name',
			renderer: render_composer_tooltip/*,
            editor: new Ext.form.ComboBox({
				store: storeComposer,	                        
				forceSelection: true,		                        
				valueField: 'object_name',
                displayField: 'object_name',                        
				typeAhead: false,		                        
				triggerAction: 'all',		                        
				pageSize: 20,		                        
				tpl: resultTplObject,		                        
				selectOnFocus: true,		                        
				editable: true,		                        
				width: 117,
                listWidth: 250,                        
				lazyRender: true,		                        
				itemSelector: 'div.search-item',		                        
				minChars: 1,	                    
		        allowBlank: true,
		        listeners: {
		            select: function(combo, record, index){
		            	gridYieldRevenue.getStore().getAt(row_current).data.composer_id = record.data.object_id;
						gridYieldRevenue.startEditing(row_current, col_current);
		            }
		        }
	        })*/
        }, singerAuthority, composerAuthority, composerRelease, {
            header: 'Số lượng',
			dataIndex: 'exchange_quantity',
            id: 'exchange_quantity',
			//width: 50,
			align: 'right',
            summaryType: 'sum',
			renderer: render_number,
            editor: new Ext.form.TextField({
                allowBlank: false,
                selectOnFocus: true,
                enableKeyEvents: true,
                listeners: {
                    keypress: function(my, e){
						if(!forceNumber(e)) e.stopEvent();
                        keyCustom(e);
                    }
                }
            })
        }, {
            header: 'Giá',
			dataIndex: 'exchange_price',
            id: 'exchange_price',
			width: 50,
			align: 'right',
			renderer: render_number,
            editor: new Ext.form.TextField({
                allowBlank: false,
                selectOnFocus: true,
                enableKeyEvents: true,
                listeners: {
                    keypress: function(my, e){
						if(!forceNumber(e)) e.stopEvent();
                        keyCustom(e);
                    }
                }
            })
        }, {
            header: 'Tổng tiền',
			dataIndex: 'money_total',
            id: 'money_total',
			renderer: render_number,
			align: 'right',
			//width: 70,
            summaryType: 'sum'
        }, {
            header: 'Phí tác giả (nhạc sĩ)',
			dataIndex: 'money_composer',
            id: 'money_composer',
			renderer: render_number,
			align: 'right',
            summaryType: 'sum'
        }, {
            header: 'Phí ghi âm (ca sĩ)',
			dataIndex: 'money_singer',
            id: 'money_singer',
			renderer: render_number,
			align: 'right',
            summaryType: 'sum'
        }, {
            header: 'Phí bên liên quan (phát hành)',
			dataIndex: 'money_release',
            id: 'money_release',
			renderer: render_number,
			align: 'right',
            summaryType: 'sum'
        }, {
            dataIndex: 'song_id',
            hidden: true
        }, {
            dataIndex: 'singer_id',
            hidden: true
        }, {
            dataIndex: 'composer_id',
            hidden: true
        }]
    });
    
    // create the Grid
    gridYieldRevenue = new Ext.grid.EditorGridPanel({
        title: '',
        store: storeYieldRevenue,
        cm: cmYieldRevenue,
        stripeRows: true,
        height: 520,
        loadMask: true,
        trackMouseOver: true,
        frame: true,
        clicksToEdit: 1,
		selModel: itemDeleter,
		plugins: [summary/*, singerAuthority, composerAuthority*/],
        tbar: tbarYieldRevenue,
        bbar: bbarYieldRevenue,
        id: 'gridYieldRevenue',
        viewConfig: {
            forceFit: true,
            deferEmptyText: true,
            emptyText: 'No records found'
        },
        listeners: {
            beforeedit: function(e){
				row_current = e.row;
                col_current = e.column;
            },
            afteredit: function(e){
				if(e.field == 'exchange_quantity' || e.field == 'exchange_price') customMoney(e);
				if (e.record.data.exchange_id > 0) {
                    updateExchange(e.record, e.field, e.value);
                }
            }
        }
    });
    
	//////
	// nhung bai hat khong co san luong doi soat trong khoang thoi gian nhu tren
	var notYieldRecord = [{
        name: 'song_id',
        type: 'string'
    }, {
        name: 'type_id',
        type: 'string'
    }, {
        name: 'partner_id',
        type: 'string'
    }, {
        name: 'singer_id',
        type: 'string'
    }, {
        name: 'singer_name',
        type: 'string'
    }, {
        name: 'composer_id',
        type: 'string'
    }, {
        name: 'composer_name',
        type: 'string'
    }, {
        name: 'song_number',
        type: 'string'
    }, {
        name: 'song_name',
        type: 'string'
    }, {
        name: 'song_unsigned_name',
        type: 'string'
    }, {
        name: 'song_price',
        type: 'string'
    }, {
        name: 'song_singer_sing',
        type: 'string'
    }, {
        name: 'song_singer_authority',
        type: 'string'
    }, {
        name: 'song_composer_authority',
        type: 'string'
    }, {
        name: 'song_release_authority',
        type: 'string'
    }, {
		name: 'partner_name',
		type: 'string'
	}, {
        name: 'ended_date',
        type: 'date'
    }, {
        name: 'created_date',
        type: 'date'
    }, {
        name: 'updated_date',
        type: 'date'
    }];
    
    var not_yield_object = Ext.data.Record.create(notYieldRecord);
    
    var storeNotYieldRevenue = new Ext.data.Store({
        reader: new Ext.data.JsonReader({
            root: 'data',
            totalProperty: 'count',
			id: 'song_id'
        }, not_yield_object),
        proxy: new Ext.data.HttpProxy({
            url: pathRequestUrl
        }),
        autoLoad: true
    });
	
	storeNotYieldRevenue.on('beforeload', function(){
        var fd = baseGetFromDateRank();
        var td = baseGetToDateRank();
        if (!isEmpty(fd) && !isEmpty(td) &&
        !isEmpty(Ext.getCmp('cbSubjectName2').getValue())) {
            storeNotYieldRevenue.baseParams.start = 0;
            storeNotYieldRevenue.baseParams.limit = page_size;
            storeNotYieldRevenue.baseParams.action = 'getNotYieldRevenue';
			storeNotYieldRevenue.baseParams.fromdate = fd;
            storeNotYieldRevenue.baseParams.todate = td;
            storeNotYieldRevenue.baseParams.partner = Ext.getCmp('cbSubjectName2').getValue();
            storeNotYieldRevenue.baseParams.object = Ext.getCmp('cbObject2').getValue();
            storeNotYieldRevenue.baseParams.type = Ext.getCmp('object_type2').getValue().inputValue;
	    
	    storeNotYieldRevenue.baseParams.partnerPrice = Ext.getCmp('cbPartnerPrices2').getRawValue();
	    storeNotYieldRevenue.baseParams.partnerPriceId = Ext.getCmp('cbPartnerPrices2').getValue();
	    					
					
            storeNotYieldRevenue.baseParams.authority = isEmpty(Ext.getCmp('cboPermission2').getValue()) ? 0 : Ext.getCmp('cboPermission2').getValue();
            storeNotYieldRevenue.baseParams.release = isEmpty(Ext.getCmp('cboRelease2').getValue()) ? -1 : Ext.getCmp('cboRelease2').getValue();
			var srchFromDate = Ext.getCmp('srch_from_date').getValue();
			if (srchFromDate != null && srchFromDate != '') 
				srchFromDate = srchFromDate.dateFormat(date_sql_format_string);
			else 
				srchFromDate = '';
			
			var srchToDate = Ext.getCmp('srch_to_date').getValue();
			if (srchToDate != null && srchToDate != '') 
				srchToDate = srchToDate.dateFormat(date_sql_format_string);
			else 
				srchToDate = '';
			storeNotYieldRevenue.baseParams.fromCreatedDate = srchFromDate;
			storeNotYieldRevenue.baseParams.toCreatedDate = srchToDate;
			storeNotYieldRevenue.baseParams.songnumber = Ext.getCmp('srch_song_number').getValue();
			storeNotYieldRevenue.baseParams.songname = Ext.getCmp('srch_song_name').getValue();
		}
    });
	
	var songSingerAuthority = new Ext.grid.CheckColumn({
        header: 'Quyền ghi âm',
        dataIndex: 'song_singer_authority'
    });
    
    var songComposerAuthority = new Ext.grid.CheckColumn({
        header: 'Quyền tác giả',
        dataIndex: 'song_composer_authority'
    });
    
    var songReleaseAuthority = new Ext.grid.CheckColumn({
        header: 'Độc quyền',
        dataIndex: 'song_release_authority'
    });
	
	var formatDate = function(value){
        if (isEmpty(value)) 
            return '';
        try {
            return value ? ((value.dateFormat('d/m/Y') != '01/01/1970') ? value.dateFormat('d/m/Y') : '') : '';
        } 
        catch (e) {
            console.debug(e);
        }
    };
	
	var cmNotYieldRevenue = new Ext.grid.ColumnModel({
        defaults: {
            sortable: false
        },
        columns: [new Ext.grid.RowNumberer(), {
            header: 'Mã Bài Hát',
            dataIndex: 'song_number'
        }, {
            header: 'Tên Bài Hát',
            dataIndex: 'song_name'
        }, {
            header: 'Ca Sĩ',
            dataIndex: 'singer_name'
        }, {
            header: 'Ca Sĩ thể hiện',
            dataIndex: 'song_singer_sing'
        }, {
            header: 'Nhạc Sĩ',
            dataIndex: 'composer_name',
            width: 120
        }, songSingerAuthority, songComposerAuthority, songReleaseAuthority, {
            header: 'Đối Tác',
            dataIndex: 'partner_name'
        }, {
			header: 'Ngày kinh doanh',
            dataIndex: 'created_date',
            renderer: formatDate
		}, {
			header: 'Ngày hết hạn',
            dataIndex: 'ended_date',
            renderer: formatDate
		}, {
			header: 'Ngày cập nhật',
            dataIndex: 'updated_date',
            renderer: formatDate
		}]
    });
	
	var cmbPerPage2 = new Ext.form.ComboBox({
        name: 'perpage2',
        width: 80,
        store: new Ext.data.SimpleStore({
            data: [[20, '20'], [50, '50'], [100, '100'], [150, '150'], [200, '200'], [250, '250'], [300, '300'], [500, '500'], [1000, '1000']],
            id: 0,
            fields: ['id', 'value']
        }),
        mode: 'local',
        value: page_size,
        listWidth: 80,
        triggerAction: 'all',
        displayField: 'value',
        valueField: 'value',
        editable: false,
        forceSelection: true
    });
    
    cmbPerPage2.on('select', function(combo, record){
        bbarNotYieldRevenue.pageSize = parseInt(record.get('id'), 10);
        bbarNotYieldRevenue.doLoad(bbarNotYieldRevenue.cursor);
    }, this);
    
    var bbarNotYieldRevenue = new Ext.PagingToolbar({
        store: storeNotYieldRevenue, //the store you use in your grid
        displayInfo: true,
        pageSize: page_size,
        items: ['-', 'Số dòng/trang', cmbPerPage2]
    });
	
	var tbarNotYieldRevenue = new Ext.Panel({
        items: [{
            xtype: 'toolbar',
            id: 'tbar1',
            items: [{
				xtype: 'label',
				text: 'Đối tác',
				style: 'padding-left: 5px; padding-right: 5px;'
			}, cbSubjectName2, cbPartnerPrices2, '-', {
				xtype: 'label',
				text: 'Tên ca sĩ/nhạc sĩ',
				style: 'padding-left: 5px; padding-right: 5px;'
			}, cbObject2, '-', {
				xtype: 'radiogroup',
				id: 'object_type2',
				value: 1,
				items: [{
					boxLabel: 'Ca sĩ',
					name: 'rb-type',
					width: 80,
					inputValue: 1
				}, {
					boxLabel: 'Nhạc sĩ',
					name: 'rb-type',
					inputValue: 2
				}],
				listeners: {
	                change: function(e){
	        			gridNotYieldRevenue.getStore().load();
	                }
	            }
			}, '-', {
				xtype: 'label',
				text: 'Loại quyền',
				style: 'padding-left: 5px; padding-right: 5px;'
			}, new Ext.form.ComboBox({
				id: 'cboPermission2',
				store: storeAuthority,
				forceSelection: true,
				displayField: 'name',
				valueField: 'authority',
				typeAhead: false,
				triggerAction: 'all',
				mode: 'local',
				allowBlank: true,
				editable: true,
				width: 100,
				minListWidth: 100,
				lazyRender: true,
				selectOnFocus: true,
				listeners: {
	                change: function(e){
	        			gridNotYieldRevenue.getStore().load();
	                }
	            }
			}), '-', {
	            xtype: 'label',
	            text: 'Độc quyền',
	            style: 'padding-left: 5px; padding-right: 5px;'
	        }, new Ext.form.ComboBox({
	            id: 'cboRelease2',
	            store: storeRelease,
	            forceSelection: true,
	            displayField: 'name',
	            valueField: 'release',
	            typeAhead: false,
	            triggerAction: 'all',
	            mode: 'local',
	            forceSelection: true,
	            triggerAction: 'all',
	            allowBlank: true,
	            editable: true,
	            width: 100,
	            minListWidth: 100,
	            lazyRender: true,
	            selectOnFocus: true,
	            listeners: {
	                select: function(combo, record, index){
	                
	                },
	                change: function(e){
	                	gridNotYieldRevenue.getStore().load();storeRelease
	                }
	            }
	        }), '->', {
				text: 'In',
				id: 'printer_add2',
				cls: 'x-btn-text-icon',
				icon: 'images/icons/printer.png',
				handler: function(){
					var action = 'exportNotYieldRevenue';
					var fromdate = baseGetFromDateRank();
					var todate = baseGetToDateRank();
					var partner = Ext.getCmp('cbSubjectName2').getValue();
					var object = Ext.getCmp('cbObject2').getValue();
					var type = Ext.getCmp('object_type2').getValue().inputValue;
					var partnerPrice = Ext.getCmp('cbPartnerPrices').getRawValue();
					var partnerPriceId = Ext.getCmp('cbPartnerPrices').getValue();
					var authority = isEmpty(Ext.getCmp('cboPermission2').getValue()) ? 0 : Ext.getCmp('cboPermission2').getValue();
					var release = isEmpty(Ext.getCmp('cboRelease2').getValue()) ? -1 : Ext.getCmp('cboRelease2').getValue();
					var srchFromDate = Ext.getCmp('srch_from_date').getValue();
					if (srchFromDate != null && srchFromDate != '') 
						srchFromDate = srchFromDate.dateFormat(date_sql_format_string);
					else 
						srchFromDate = '';					
					var srchToDate = Ext.getCmp('srch_to_date').getValue();
					if (srchToDate != null && srchToDate != '') 
						srchToDate = srchToDate.dateFormat(date_sql_format_string);
					else 
						srchToDate = '';
					var fromCreatedDate = srchFromDate;
					var toCreatedDate = srchToDate;
					
					var songnumber = Ext.getCmp('srch_song_number').getValue();
					var songname = Ext.getCmp('srch_song_name').getValue();
			
					window.open(pathRequestUrl + '?action=' + action +
						    '&partner=' + partner +
						    '&object=' + object +
						    '&partnerPrice=' + partnerPrice +
						    '&partnerPriceId=' + partnerPriceId +
					'&type=' + type +
					'&authority=' + authority + '&release=' + release + '&fdate=' + fromdate + '&tdate=' + todate + '&fcreateddate=' + fromCreatedDate + '&tcreateddate=' + toCreatedDate +
					'&songnumber=' + songnumber + '&songname=' + songname, null, "height=200,width=400,status=yes,toolbar=no,menubar=no,location=no");
				}
			}, '-', {
				text: 'Tải lại',
				id: 'reload_detail2',
				iconCls: 'btn-text-icon',
				icon: './images/icons/refresh.png',
				handler: function(){
					storeNotYieldRevenue.removeAll();
					storeNotYieldRevenue.load();
				}
			}]
		}, {
			xtype: 'toolbar',
            id: 'tbar2',
            items: [{
				xtype: 'label',
				text: 'Ngày kinh doanh: Từ ngày',
				style: 'padding-left: 5px; padding-right: 5px;'
			}, {
				xtype: 'datefield',
				width: 99,
				labelSeparator: '',
				id: 'srch_from_date',
				format: date_format_string,
				//readOnly: true,
				vtype: 'daterange',
				endDateField: 'srch_to_date'
			}, '-', {
				xtype: 'label',
				text: 'Đến ngày',
				style: 'padding-left: 5px;padding-right: 5px;'
			}, {
				xtype: 'datefield',
				width: 99,
				labelSeparator: '',
				id: 'srch_to_date',
				format: date_format_string,
				//readOnly: true,
				vtype: 'daterange',
				startDateField: 'srch_from_date'
			}, '-', {
                xtype: 'tbtext',
                width: 60,
                text: 'Mã Bài Hát '
            }, {
                xtype: 'textfield',
                id: 'srch_song_number',
                width: 100
            }, '-', {
                xtype: 'tbtext',
                width: 65,
                text: 'Tên Bài Hát ',
            }, {
                xtype: 'textfield',
                id: 'srch_song_name',
                width: 100
            }]
		}]
	});
	
	gridNotYieldRevenue = new Ext.grid.EditorGridPanel({
        title: '',
        store: storeNotYieldRevenue,
        cm: cmNotYieldRevenue,
        stripeRows: true,
        height: 520,
        loadMask: true,
        trackMouseOver: true,
        frame: true,
        clicksToEdit: 1,
		selModel: itemDeleter,
		//plugins: [summary, singerAuthority, composerAuthority],
        sm: new Ext.grid.RowSelectionModel({
            singleSelect: false
        }),
        tbar: tbarNotYieldRevenue,
        bbar: bbarNotYieldRevenue,
        id: 'gridNotYieldRevenue',
        viewConfig: {
            forceFit: true,
            deferEmptyText: true,
            emptyText: 'No records found'
        }
    });
	
	//////	
	
	var tabs = new Ext.TabPanel({
        id: 'tabs',
        enableTabScroll: true,
        activeTab: 0,
        frame: true,
        defaults: {
            autoHeight: true
        },
        items: [{
            title: "Có sản lượng",
            id: 'listYieldRevenue',
            items: [gridYieldRevenue]
		}, {
            title: "Không sản lượng",
            id: 'songNotYieldRevenue',
            items: [gridNotYieldRevenue]
        }]
    });
	
    var productBalanceTable = new Ext.FormPanel({
        frame: true,
        title: 'Thông kê sản lượng doanh thu của ca, nhạc sỹ',
        width: 1100,
        renderTo: 'YieldRevenueInformationTables',
        iconCls: 'form-icon',
        items: [generalTab, tabs]
    });
    
    var baseGetFromDateRank = function(){
        var type = Ext.getCmp('timename').getValue().inputValue;
        switch (type) {
            case 'month':
                var m = Ext.getCmp('month2').getValue().toString();
                if (m.length < 2) {
                    m = '0' + m;
                }
                var d = Ext.getCmp('year2').getValue() + '/' + m + '/02';
                return (new Date(d)).getFirstDateOfMonth().dateFormat(date_sql_format_string);
                break;
            case 'quarter': // quy
                var q = Ext.getCmp('quarter3').getValue();
                var y = Ext.getCmp('year3').getValue();
                var d = '';
                if (q == 1) {
                    d = y + '/01/02';
                }
                else 
                    if (q == 2) {
                        d = y + '/04/02';
                    }
                    else 
                        if (q == 3) {
                            d = y + '/07/02';
                        }
                        else 
                            if (q == 4) {
                                d = y + '/10/02';
                            }
                return (new Date(d)).getFirstDateOfMonth().dateFormat(date_sql_format_string);
                break;
            case 'frommonth': // tu thang
                var fm = Ext.getCmp('frommonth7').getValue().toString();
                if (fm.length < 2) {
                    fm = '0' + fm;
                }
                var fy = Ext.getCmp('fromyear7').getValue();
                var d = fy + '/' + fm + '/02';
                return (new Date(d)).getFirstDateOfMonth().dateFormat(date_sql_format_string);
                break;
            default:
                console.debug('fail');
        }
    };
    
    var baseGetToDateRank = function(){
        var type = Ext.getCmp('timename').getValue().inputValue;
        switch (type) {
            case 'month':
                var m = Ext.getCmp('month2').getValue().toString();
                if (m.length < 2) {
                    m = '0' + m;
                }
                var d = Ext.getCmp('year2').getValue() + '/' + m + '/02';
                return (new Date(d)).getLastDateOfMonth().dateFormat(date_sql_format_string);
                break;
            case 'quarter': // quy
                var q = Ext.getCmp('quarter3').getValue();
                var y = Ext.getCmp('year3').getValue();
                var d = '';
                if (q == 1) {
                    d = y + '/03/02';
                }
                else 
                    if (q == 2) {
                        d = y + '/06/02';
                    }
                    else 
                        if (q == 3) {
                            d = y + '/09/02';
                        }
                        else 
                            if (q == 4) {
                                d = y + '/12/02';
                            }
                return (new Date(d)).getLastDateOfMonth().dateFormat(date_sql_format_string);
                break;
            case 'frommonth':
                var tm = Ext.getCmp('tomonth7').getValue().toString();
                if (tm.length < 2) {
                    tm = '0' + tm;
                }
                var ty = Ext.getCmp('toyear7').getValue();
                var d = ty + '/' + tm + '/02';
                return (new Date(d)).getLastDateOfMonth().dateFormat(date_sql_format_string);
                break;
            default:
                console.debug('fail');
        }
    };
    
});

/**
 * ---------------------------------------------------------
 * Update
 * @author huudatxm
 */
var updateExchange = function(record, field, value){
//	if(field == 'song_number' || field == 'song_name') {
//		field = 'song_id';
//		value = record.data.song_id;
//	}else if(field == 'singer_name') {
//		field = 'singer_id';
//		value = record.data.singer_id;
//	}else if(field == 'composer_name') {
//		field = 'composer_id';
//		value = record.data.composer_id;
//	}
	if(field == 'exchange_price' || field == 'exchange_quantity'){
		value = cN(value);
	}
    Ext.Ajax.request({
        url: pathRequestUrl,
        method: 'post',
        success: function(res, opt){
            var result = Ext.decode(res.responseText);
            if (result.data) {
                record.commit();
            }
        },
        failure: function(response, request){
            var data = Ext.decode(response.responseText);
            if (!data.success) {
                alert(data.error);
                return;
            }
        },
        params: {
            action: 'update',
            field: field,
            value: value,
            exchange_id: record.data.exchange_id
        }
    });
};

/**
 * Key Control
 * @author datnh
 */
var keyCustom = function(e){
    if (e.keyCode == 40) {
        //KeyDown	
        var store_size = gridYieldRevenue.getStore().getCount();
        if ((store_size - 1) == row_current) return false;
        row_current++;
        gridYieldRevenue.startEditing(row_current, col_current);
        gridYieldRevenue.getSelectionModel().selectRow(row_current);
    } else if (e.keyCode == 38) {
        //KeyUp
        if (row_current > 0) {
            row_current--;
            gridYieldRevenue.startEditing(row_current, col_current);
            gridYieldRevenue.getSelectionModel().selectRow(row_current);
        }
    }
};
/**
 * Set value again for money 
 * 
 */

var customMoney = function(e) {
	var exchange_quantity = cN(e.record.data.exchange_quantity);
	var exchange_price = cN(e.record.data.exchange_price);
	var money_total = exchange_quantity * exchange_price;
	e.record.data.money_total = money_total;
	e.record.data.money_composer = money_total * 0.4;
	e.record.data.money_singer = money_total * 0.3;
	e.record.data.money_release = money_total * 0.3;
	e.record.commit();
};

/**
 * Delete
 * @author huudatxm
 */
var deleteExchange = function(record){
    Ext.Ajax.request({
        url: pathRequestUrl,
        method: 'post',
        success: function(res, opt){
            var result = Ext.decode(res.responseText);
            if (result.data) {
            	gridYieldRevenue.getStore().remove(record);
            	gridYieldRevenue.getView().refresh();
            }
            else {
                alert('Không thể xóa vì lỗi phát sinh.');
            }
        },
        failure: function(response, request){
            var data = Ext.decode(response.responseText);
            if (!data.success) {
                alert(data.error);
                return;
            }
        },
        params: {
            action: 'delete',
            exchange_id: record.data.exchange_id
        }
    });
};
